package com.ciwong.epaper.util;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Color;
import android.os.Build;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.Window;
import android.view.WindowManager;

import com.android.volley.AuthFailureError;
import com.android.volley.NoConnectionError;
import com.android.volley.TimeoutError;
import com.ciwong.epaper.R;
import com.ciwong.epaper.widget.TeacherCommentDialog;
import com.ciwong.epaper.widget.TopWarningMsgDialog;
import com.ciwong.mobilelib.ui.BaseActivity;
import com.ciwong.mobilelib.utils.ToastUtil;
import com.ciwong.mobilelib.utils.XXPermissionTool;
import com.ciwong.mobilelib.widget.CWDialog;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 错误Dialog工具
 *
 * @author sugy
 * @version ciwong v.1.0 2016/1/13 15:32
 * @since ciwong v.1.0
 */
public class DialogUtil {

    /**
     * 显示错误弹出框
     *
     * @param activity
     * @param data     失败信息
     */
    public static void showErrorDialog(Activity activity, Object data) {
        if (activity.isFinishing()) {
            return;
        }
        if (data == null) {
            showDialog(activity, R.string.unknown_error);
        } else if (data instanceof NoConnectionError) {
            showDialog(activity, R.string.connect_disable);
        } else if (data instanceof TimeoutError) {

//            showDialog(activity, R.string.connect_timeout);

        } else if (data instanceof String) {

            String dataStr = data.toString();
            showDialog(activity, TextUtils.isEmpty(dataStr)
                    ? activity.getString(R.string.unknown_error) : dataStr);
        } else if (data instanceof Integer) {
            int resId = (int) data;
            showDialog(activity, resId == 0 ? R.string.unknown_error : resId);
        } else {
            showDialog(activity, R.string.unknown_error);
        }
    }


    public static void showErrorDialog(Activity activity, int errorCode, Object data) {
        if (errorCode == 17 | errorCode == 27) {
            return;
        }
        String dataStr = data.toString();
        showDialog(activity, TextUtils.isEmpty(dataStr)
                ? activity.getString(R.string.unknown_error) : dataStr);
    }


    /**
     * 显示错误提示框
     *
     * @param activity
     * @param resId
     */
    private static void showDialog(Activity activity, int resId) {
        showDialog(activity, activity.getString(resId));
    }

    /**
     * 显示错误提示框
     *
     * @param activity
     * @param resId
     */
    private static void showDialog(Activity activity, String resId) {
        if (activity.isFinishing()) {
            return;
        }
        final CWDialog errorDialog = new CWDialog(activity);
        errorDialog.setMessage(resId)
                .setPositiveButton(activity.getString(android.R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                errorDialog.dismiss();
                            }
                        }, true,
                        activity.getResources()
                                .getDrawable(R.drawable.dialog_floor_selector))
                .show();
    }

    /**
     * 显示空间不足错误提示框
     */
    public static void showSdFullDialog(Activity activity, String fileSize) {

//        MeUtil.getScale(Double.parseDouble(fileSize) * EConstants.DOWNLOAD_SIZE_MULTIPLE)

        final CWDialog errorDialog = new CWDialog(activity);
        errorDialog
                .setMessage(!TextUtils.isEmpty(fileSize)
                        ? activity.getString(R.string.error_sd_full_download)

                        : activity.getString(R.string.error_sd_full_do_work))
                .setPositiveButton(activity.getString(android.R.string.ok),
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                errorDialog.dismiss();
                            }
                        }, true,
                        activity.getResources()
                                .getDrawable(R.drawable.dialog_floor_selector))
                .show();
    }


    public static void showTopHintDialog(Context context, String topHintMsg, int topOffset) {

        TopWarningMsgDialog mTopWarningMsgDialog = new TopWarningMsgDialog(context, topHintMsg);
        // dialog.setTitle("操作提醒");
        Window dialogWindow = mTopWarningMsgDialog.getWindow();
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        WindowManager.LayoutParams params = mTopWarningMsgDialog.getWindow().getAttributes();
        if (topOffset > 0) {
            params.y = DisplayUtils.dip2px(context, topOffset);
        } else {
            //45 是标题栏高度，在标题栏下面
            params.y = DisplayUtils.dip2px(context, 45);
        }
        params.x = 0;
        dialogWindow.setAttributes(params);
        mTopWarningMsgDialog.setCanceledOnTouchOutside(true); //点击dialog区域之外的地方，dialog消失
        mTopWarningMsgDialog.show();
    }


    public static void showTopHintDialogWithAnim(Context context, String topHintMsg, int topOffset) {

        TopWarningMsgDialog mTopWarningMsgDialog = new TopWarningMsgDialog(context, topHintMsg);

        Window dialogWindow = mTopWarningMsgDialog.getWindow();

        dialogWindow.setWindowAnimations(R.style.dialog_window_anim); //设置窗口弹出动画
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        WindowManager.LayoutParams params = mTopWarningMsgDialog.getWindow().getAttributes();

        if (topOffset > 0) {
            params.y = DisplayUtils.dip2px(context, topOffset);
        } else {
            //45 是标题栏高度，在标题栏下面
            params.y = DisplayUtils.dip2px(context, 45);
        }
        params.x = 0;
        dialogWindow.setAttributes(params);
        mTopWarningMsgDialog.setCanceledOnTouchOutside(true); //点击dialog区域之外的地方，dialog消失
        mTopWarningMsgDialog.show();
    }


    /**
     * 退出提示框
     */
    public static void showConfirmEndDialog(final Activity context) {
        CWDialog dialog = new CWDialog(context);
        dialog.setMessage(R.string.confirm_back_work);
        dialog.setPositiveButton(android.R.string.cancel, null)
                .setNegativeButton(R.string.ok,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog,
                                                int which) {
                                dialog.dismiss();

                                context.finish();
                            }
                        })
                .show();
    }

    public static void showCommentDialog(Context context, String comment) {
        TeacherCommentDialog dialog = new TeacherCommentDialog(context, comment);
        // dialog.setTitle("操作提醒");
        Window dialogWindow = dialog.getWindow();
        dialogWindow.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        dialogWindow.setGravity(Gravity.CENTER_HORIZONTAL | Gravity.TOP);
        WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.y = DisplayUtils.dip2px(context, 60);
        params.x = 0;
        //加这个标志位 为了弹出对话框是背景变暗
        params.flags = WindowManager.LayoutParams.FLAG_DIM_BEHIND;

        dialogWindow.setAttributes(params);
        dialog.setCanceledOnTouchOutside(true); //点击dialog区域之外的地方，dialog消失
        dialog.show();
    }


    public static void showFailedToastByErrorType(Context context, Object data) {

        if (data == null) {

//            CWToast.makeText(context,
//                    R.string.unknown_error, Toast.LENGTH_LONG,
//                    true).setToastType(CWToast.TOAST_TYPE_ERROR)
//                    .show();

            return;
        } else if (data instanceof AuthFailureError) {

            if (null != context) {
                ToastUtil.INSTANCE.toastCenterError(R.string.token_expire);
            }


        } else if (data instanceof NoConnectionError) {

//            CWToast.makeText(context,
//                    R.string.connect_disable, Toast.LENGTH_LONG,
//                    true).setToastType(CWToast.TOAST_TYPE_ERROR)
//                    .show();

        } else if (data instanceof TimeoutError) {

            //超时不显示，因为隔很久就显示，干扰用户
//            CWToast.makeText(context,
//                    R.string.connect_timeout, Toast.LENGTH_LONG,
//                    true).setToastType(CWToast.TOAST_TYPE_ERROR)
//                    .show();

        } else {
//            FeedbackUtil.getInstance().addFeedbackLog(FeedbackUtil.FEEDBACK_TYPE_REQUEST_ERROR, data.toString(), "请求错误");

        }


    }

    public static void showSettingPermissions(final BaseActivity context) {
//        if (!XXPermissionTool.isHasPermission(context, Manifest.permission.RECORD_AUDIO)) {
//            RecordPermissionsDialog recordPermissionsDialog = new RecordPermissionsDialog(context);
//            recordPermissionsDialog.show();
//        }
        showgetRecordPermissDialog(context);
    }

    private static final int CODE_REQUEST_RECORD_AUDIO_PERMISSION = 8801;

    private static CWDialog getRecordPermissDialog;

    /**
     * 获取Record权限提示框
     */
    private static boolean showgetRecordPermissDialog(final BaseActivity context) {
        boolean isHavePermiss = XXPermissionTool.isHasPermission(context, Manifest.permission.RECORD_AUDIO);
        if (isHavePermiss) {
            checkRecordAudioPermiss(context);
        } else {
            if (getRecordPermissDialog == null) {
                getRecordPermissDialog = new CWDialog(context);
                getRecordPermissDialog.setTitle(R.string.get_permiss_title);
                getRecordPermissDialog.setTitleTextColor(Color.BLACK);
                getRecordPermissDialog.setMessage(context.getString(R.string.get_record_permiss_content), 16, Color.BLACK, Gravity.LEFT);
                getRecordPermissDialog.setPositiveButton(R.string.get_permiss_ok, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                        checkRecordAudioPermiss(context);
                    }
                });
                getRecordPermissDialog.setNegativeButton(R.string.get_permiss_no, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        getRecordPermissDialog.dismiss();
                    }
                });
            }
            getRecordPermissDialog.show();
        }
        return true;
    }

    /**
     * 使用录音，判断权限
     */
    private static boolean checkRecordAudioPermiss(final BaseActivity context) {
        if (Build.VERSION.SDK_INT >= 23
                && context.getApplicationInfo().targetSdkVersion >= 23) {
            List<String> permissionList = new ArrayList<String>();
            Map<String, String> noteMap = new HashMap<>();
            permissionList.add(Manifest.permission.RECORD_AUDIO);
            noteMap.put(Manifest.permission.RECORD_AUDIO, "录音权限");
            XXPermissionTool.checkPermissions(context, //
                    permissionList, //
                    noteMap, //
                    CODE_REQUEST_RECORD_AUDIO_PERMISSION, //
                    new XXPermissionTool.OnCheckPermissionsFinishedListener() {
                        @Override
                        public void onCheckPermissionsFinished(int flag) {
                            if (0 == flag) {
//                                record();
                            } else {
//                                showConfirmCommitDialog(getActivity(), "未获取到读写本地存储权限。");
                            }
                        }
                    });
        } else {
            return true;
        }
        return true;
    }
}
